package com.itheima.framework.config;



import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;

/**
 * MyBatis配置（支持MyBatis-Plus）
 *
 * @author ruoyi
 */
@Configuration
@MapperScan(basePackages = "com.itheima.**.mapper",
        annotationClass = Mapper.class, // 只扫描带有@Mapper注解的接口
        sqlSessionFactoryRef = "sqlSessionFactory")
public class MyBatisConfig {

    // 支持MyBatis-Plus和MyBatis两种配置方式
    @Value("${mybatis-plus.type-aliases-package:${mybatis.typeAliasesPackage:com.itheima.**.domain}}")
    private String typeAliasesPackage;

    @Value("${mybatis-plus.mapper-locations:${mybatis.mapperLocations:classpath*:mapper/**/*Mapper.xml}}")
    private String mapperLocations;

    @Value("${mybatis-plus.config-location:${mybatis.configLocation:}}")
    private String configLocation;

    /**
     * MyBatis-Plus拦截器（分页等）
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

    /**
     * SQL会话工厂
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        // 使用MyBatis-Plus的SqlSessionFactoryBean
        com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean bean = 
            new com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        // 设置别名包
        if (StringUtils.hasText(typeAliasesPackage)) {
            bean.setTypeAliasesPackage(typeAliasesPackage);
        } else {
            // 默认包路径
            bean.setTypeAliasesPackage("com.itheima.**.domain");
        }

        // 设置Mapper位置
        if (StringUtils.hasText(mapperLocations)) {
            Resource[] resources = new PathMatchingResourcePatternResolver().getResources(mapperLocations);
            bean.setMapperLocations(resources);
        }

        // 设置配置文件位置
        if (StringUtils.hasText(configLocation)) {
            Resource resource = new DefaultResourceLoader().getResource(configLocation);
            bean.setConfigLocation(resource);
        }

        return bean.getObject();
    }
}
